﻿using System;
using System.Windows;
using BrainTechLLC.Silverlight.InputControls;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;

namespace BrainTechLLC.Silverlight.ClientApplication
{
    public partial class InputSearchCriteria : UserControl
    {
        public event EventHandler<ObjectEventArgs<Type>> TypeChanged;
        public event EventHandler<ObjectEventArgs<SearchCriteria>> SearchRequested;

        public InputSearchCriteria()
        {
            // Required to initialize variables
            InitializeComponent();
            txtSearch.AttachFocusWatcher();
            txtIDs.AttachFocusWatcher();
        }

        private void typeFilter_TypeChanged(object sender, ObjectEventArgs<Type> e)
        {
            if (TypeChanged != null)
                TypeChanged(sender, e);
        }

        public void ReflectIDsInTextbox(ObservableCollection<object> objs)
        {
            CommaList c = new CommaList();
            foreach (var obj in objs)
            {
                c.AddValue((obj as IGameThing).AssociatedID.ToString());
            }
            txtIDs.Text = c.ToString();
        }

        public SearchCriteria GetCurrentSearchCritera()
        {
            return GetSearchCriteria(chkShowOnlyListed.IsChecked == true);
        }

        public SearchCriteria GetSearchCriteria(bool useCommaList)
        {
            SearchCriteria result = new SearchCriteria();
            if (useCommaList)
            {
                CommaList c = CommaList.CreateFromCommaDelimited(txtIDs.Text);
                result.IDs = c.GetReadOnlyList<long>();
            }
            if (typeFilter.CurrentSelectedType != null)
            {
                result.Type = typeFilter.CurrentSelectedType;
            }
            if (!string.IsNullOrEmpty(txtSearch.Text))
            {
                result.Keywords = txtSearch.Text;
            }
            return result;
        }

        public void OnSearchRequested()
        {
            if (SearchRequested != null)
                SearchRequested(this, new ObjectEventArgs<SearchCriteria>(GetSearchCriteria(chkShowOnlyListed.IsChecked == true)));
        }

        private void btnFind_Click(object sender, RoutedEventArgs e)
        {
            OnSearchRequested();
        }

        private void CheckBox_Checked(object sender, RoutedEventArgs e)
        {

        }

        private void txtSearch_KeyDown(object sender, KeyEventArgs e)
        {            
            if (e.Key == Key.Enter)
            {
                OnSearchRequested();
                e.Handled = true;
            }
        }
    }
}